<template>
    <div class='app-container'>
        <el-segmented
            v-model="policeAreaId"
            :options="segmentedList"
            @change="segmentedChangeHandle"
        >
            <template #default="{ item }">
                <div class="flex flex-col items-center gap-2 p-2">
                    <div>{{ item.label }}</div>
                </div>
            </template>
        </el-segmented>

        <el-divider/>

        <div v-loading="loading">
            <FullCalendar
                ref="fullCalendarRef"
                :options="calendarOptions"
            />
        </div>
    </div>

    <AddEditSchedule ref="scheduleRef" @refreshData="getScheduleList"/>
    <ScheduleDetail ref="scheduleDetailRef"/>
</template>
<script setup>
import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interactionPlugin from "@fullcalendar/interaction";
import esLocale from '@fullcalendar/core/locales/zh-cn';
import dayjs from "dayjs";
import AddEditSchedule from "@/views/PoliceWork/SetSchedu/components/AddEditSchedule.vue";
import {ElMessage} from "element-plus";
import {getPoliceAreaList} from "@/api/PoliceAreaManage/PoliceAreaManage.js";
import useUserStore from "@/store/modules/user.js";
import {getPoliceScheduleLiteApi} from "@/api/SetSchedule/SetSchedule.js";
import ScheduleDetail from "@/views/PoliceWork/SetSchedu/components/ScheduleDetail.vue";
import {useTemplateRef} from "vue";

const loading = ref(false)
const policeAreaId = ref('')
const segmentedList = ref([])

const scheduleRef = useTemplateRef('scheduleRef')
const scheduleDetailRef = useTemplateRef('scheduleDetailRef')
const fullCalendarRef = useTemplateRef('fullCalendarRef')

const todayDate = dayjs().startOf("day");
const TODAY = todayDate.format("YYYY-MM-DD");

// 获取当前月份的第一天
const firstDay = dayjs().startOf("month").format("YYYY-MM-DD");
// 获取当前月份的最后一天
const lastDay = dayjs().endOf("month").format("YYYY-MM-DD");

const queryParams = ref({
    unitId: useUserStore().info.unitId,
    params: {
        beginTime: firstDay,
        endTime: lastDay,
    },
    policeareaId: ''
})

const calendarOptions = ref({
    plugins: [dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin],
    // 头部内容
    headerToolbar: {
        left: "title",
        center: "",
        right: "prev,next today",
        // right: false
    },
    customButtons: {
        prev: {
            text: 'prev',
            click: function () {
                calendarDateEventHandle('prev');

            }
        },
        next: {
            text: 'next',
            click: function () {
                calendarDateEventHandle('next');
            }
        },
        today: {
            text: '今日',
            click: function () {
                calendarDateEventHandle('today');
            }
        }
    },

    // 日历首次加载时显示的初始日期
    initialDate: TODAY,
    navLinks: false, // can click day/week names to navigate views
    selectable: false,
    selectMirror: true,

    editable: false,
    dayMaxEvents: true, // allow "more" link when too many events

    // 语音化
    locale: esLocale,

    dayCellDidMount: (info) => {
        const today = new Date();
        const cellDate = new Date(info.date);

        // 如果该日期在今天之前
        if (cellDate < today) {
            info.el.style.backgroundColor = 'white'; // 将背景颜色设置为灰色
            // info.el.style.pointerEvents = 'none'; // 禁用点击事件
            info.el.style.opacity = '0.6'; // 添加透明度，视觉上更明显
        }

    },
    events: [],

    // 使用 eventContent 来自定义事件渲染
    eventContent: (arg) => {
        return {
            html: `<div class="fc-event-title fc-custom-content" title="${arg.event.title}">${arg.event.title}</div>`
        };

    },
    // 用户点击了日期
    dateClick: (info) => {

        // 禁止点击今天之前的日期
        if (isBeforeToday(info.dateStr)) {
            // 这里可以加个提示，提示用户不能点击过去的日期
            ElMessage.error("没有权限对以前日期进行编辑！");
            return;
        }

        const data = {
            date: dayjs(info.date).format('YYYY-MM-DD'),
            policeAreaId: policeAreaId.value
        }
        console.log("点击了有效日期：", data);

        scheduleRef.value.showAddSchedule(data)
        //     alert('Clicked on: ' + info.dateStr);
        //     alert('Coordinates: ' + info.jsEvent.pageX + ',' + info.jsEvent.pageY);
        //     alert('Current view: ' + info.view.type);
        //     // change the day's background color just for fun
        //     info.dayEl.style.backgroundColor = 'red';
    },

    // 当用户点击事件时触发
    eventClick: (info) => {
        if (isBeforeToday(info.event.startStr)) {
            scheduleDetailRef.value.showScheduleDetail(info.event.extendedProps.scheduleId)
            return ''
        }

        scheduleRef.value.showEditSchedule(info.event.extendedProps.scheduleId)
    }
})

// 日历时间回掉事件
const calendarDateEventHandle = async (direction) => {
    const calendarApi = fullCalendarRef.value.getApi();
    let currentDate = dayjs(calendarApi.getDate()); // 获取当前视图的日期

    let startOfMonth, endOfMonth;

    if (direction === 'prev') {
        // 获取上个月的开始和结束日期
        startOfMonth = currentDate.subtract(1, 'month').startOf('month');
        endOfMonth = currentDate.subtract(1, 'month').endOf('month');
        calendarApi.prev();
    } else if (direction === 'next') {
        // 获取下个月的开始和结束日期
        startOfMonth = currentDate.add(1, 'month').startOf('month');
        endOfMonth = currentDate.add(1, 'month').endOf('month');
        calendarApi.next();
    } else if (direction === 'today') {
        // 获取当前月的开始和结束日期
        currentDate = dayjs(); // 获取当前日期（今天）
        startOfMonth = currentDate.startOf('month');
        endOfMonth = currentDate.endOf('month');
        calendarApi.today();
    }

    // 更新 queryParams 的时间参数
    queryParams.value.params.beginTime = startOfMonth.format('YYYY-MM-DD');
    queryParams.value.params.endTime = endOfMonth.format('YYYY-MM-DD');

    await getScheduleList()
}


// 设置日历的数据配置
const setCalendarOptions = (data) => {
    calendarOptions.value.events = data
}

// 警务区列表
const policeAreaList = ref([])

// 获取办案区
const getPoliceArea = async () => {
    const res = await getPoliceAreaList({
        unitId: useUserStore().info.unitId
    })
    segmentedList.value = res.rows.map(item => {
        return {
            label: item.areaname,
            value: item.policeareaId,
        }
    });

    //
    policeAreaId.value = segmentedList.value[0].value;
    queryParams.value.policeareaId = segmentedList.value[0].value;
}


// 警务区变更
const segmentedChangeHandle = (data) => {
    policeAreaId.value = data
    queryParams.value.policeareaId = data
    getScheduleList()
}

// 获取日程列表
const getScheduleList = async () => {
    // console.log(segmented.value)
    loading.value = true;
    const res = await getPoliceScheduleLiteApi(queryParams.value)

    const options = res.data.map(item => {
        const startTime = dayjs(item.startdate).format('HH:mm');
        const endTime = dayjs(item.enddate).format('HH:mm');
        const userList = item.jwSendpoliceList.map(item => item.userName).join(',')
        return {
            scheduleId: item.jwScheduleId,
            title: `${startTime}-${endTime} ${userList}`,
            //"10:12-17:12：罗衍宁,罗衍宁",
            className: 'fc-custom',
            start: item.startdate,
            end: item.enddate
        }
    });
    // 给日历设置数据
    setCalendarOptions(options)
    // console.log('getScheduleList res', JSON.stringify(res.data))
    loading.value = false;
}

// 检测时间是否是在今日之前
const isBeforeToday = (time) => {
    const today = new Date();
    const clickedDate = new Date(time);

    return clickedDate < today.setHours(0, 0, 0, 0);
}
onMounted(() => {
    getPoliceArea().then(() => {
        getScheduleList()
    })
})

</script>

<style lang="scss">
.fc-header-toolbar {
    font-size: 0.75rem;
}

.fc-custom {
    position: relative;
    white-space: revert;

    .fc-daygrid-event-dot, .fc-event-time {
        display: none
    }
}

.fc-custom-content {
    color: var(--el-color-primary-dark-5);
    border-bottom: 1px dotted var(--el-color-primary-light-6);
}

.fc .fc-daygrid-day.fc-day-today {
    background-color: var(--el-color-success-light-5) !important;
    opacity: 1;
}

.fc-theme-standard .fc-popover {
    opacity: 1 !important;
}
</style>